package cn.iocoder.yudao.module.esim.util;

import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.Base64;
import javax.imageio.ImageIO;

import cn.hutool.extra.qrcode.BufferedImageLuminanceSource;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.LuminanceSource;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.Result;
import com.google.zxing.common.HybridBinarizer;
import lombok.extern.slf4j.Slf4j;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.common.BitMatrix;

import java.io.ByteArrayOutputStream;

@Slf4j
public class QRCodeUtil {

    public static void main(String[] args) throws Exception {
//        String base64Image = FileUtil.readString("E:/cardkey/image.text", "utf-8");
//        String decodedText = decodeQRCodeFromBase64(base64Image);

//        byte[] imageBytes = FileUtil.readBytes("E:/cardkey/image.png");
//        String decodedText = decodeQRCodeFromImageByte(imageBytes);
//        System.out.println("二维码内容: " + decodedText);

        String data = "LPA:1$rsp-0001.linksfield.net$E8S1O-H9UX2-K8XYR-SNQ5J"; // 要编码成二维码的数据
        int width = 300; // 二维码宽度
        int height = 300; // 二维码高度
        String format = "png"; // 二维码图片格式

        String base64Image = generateQRCodeBase64(data, width, height, format);
        System.out.println(base64Image);
    }

    public static String generateQRCodeBase64(String data, int width, int height, String format) {
        String base64Image = null;
        ByteArrayOutputStream outputStream = null;
        try {
            // 使用MultiFormatWriter类编写二维码数据
            BitMatrix bitMatrix = new MultiFormatWriter().encode(data, BarcodeFormat.QR_CODE, width, height);

            // 将BitMatrix对象转换为BufferedImage对象
            BufferedImage bufferedImage = toBufferedImage(bitMatrix);

            // 将BufferedImage对象转换为字节数组
            outputStream = new ByteArrayOutputStream();
            ImageIO.write(bufferedImage, format, outputStream);

            // 将字节数组转换为Base64字符串
            base64Image = Base64.getEncoder().encodeToString(outputStream.toByteArray());
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            // 关闭输出流
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    log.warn("生成二维码-关闭输出流异常", e);
                }
            }
        }
        return base64Image;
    }

    // 将BitMatrix对象转换为BufferedImage对象
    private static BufferedImage toBufferedImage(BitMatrix matrix) {
        int width = matrix.getWidth();
        int height = matrix.getHeight();
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                image.setRGB(x, y, matrix.get(x, y) ? 0xFF000000 : 0xFFFFFFFF);
            }
        }
        return image;
    }

    // 解析二维码
    public static String decodeQRCodeFromBase64(String base64Image) {
        // 解码 base64 文本为字节数组
        final byte[] imageBytes = Base64.getDecoder().decode(base64Image);
        return decodeQRCodeFromImageByte(imageBytes);
    }

    public static String decodeQRCodeFromImageByte(byte[] imageBytes) {
        try {
            // 创建 ByteArrayInputStream 以读取字节数组
            ByteArrayInputStream bis = new ByteArrayInputStream(imageBytes);
            // 使用 ImageIO 读取 BufferedImage
            BufferedImage image = ImageIO.read(bis);
            bis.close();

            // 创建 LuminanceSource 对象，用于提供图像数据给二维码解析器
            LuminanceSource source = new BufferedImageLuminanceSource(image);
            BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));

            // 创建 MultiFormatReader 对象，用于解析图像中的二维码
            MultiFormatReader reader = new MultiFormatReader();

            // 解析二维码并返回结果
            Result result = reader.decode(bitmap);
            return result.getText();
        } catch (Exception e) {
            log.error("解析二维码失败", e);
            throw new RuntimeException(e);
        }
    }
}
